var gLocalSearch;
var gMap;
var gCurrentResults = [];
var marker;

function doSearch() {
  var query = document.getElementById("queryInput").value;
  gLocalSearch.setCenterPoint(gMap.getCenter());
  gLocalSearch.execute(query);
}

// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() {
  if (!gLocalSearch.results) return;

  // Clear the map
  for (var i = 0; i < gCurrentResults.length; i++) {
    gCurrentResults[i].marker().setMap(null);
  }

  gCurrentResults = [];
  gCurrentResults.push(new LocalResult(gLocalSearch.results[0]));

  // Move the map to the first result
  var first = gLocalSearch.results[0];
  gMap.setCenter(new google.maps.LatLng(parseFloat(first.lat), parseFloat(first.lng)));
}

// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result) { 
  var me = this;
  me.result_ = result;
  me.marker_ = me.marker();
}

// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function() {
  var me = this;
  if (me.marker_) return me.marker_;
  marker = me.marker_ = new google.maps.Marker({
    position: new google.maps.LatLng(parseFloat(me.result_.lat), parseFloat(me.result_.lng)),
    map: gMap,
	draggable: true
  });
  
  document.getElementById('lat').value = marker.get('position').lat();
  document.getElementById('lng').value = marker.get('position').lng();
  
  google.maps.event.addListener(marker, 'dragend', function() {
	document.getElementById('lat').value = this.get('position').lat();
	document.getElementById('lng').value = this.get('position').lng();
  });
  
  return marker;
};